
import pymysql

host='localhost'
port=3308
user='root'
password='123456'
database='market'
charset='utf8'



# 连接数据库
def get_conn():
    db=pymysql.Connect(host=host,port=port,user=user,password=password,database=database,charset=charset)
    # print('数据库已连接')
    return db
# 查询数据库
def read_data(sql):
    db=get_conn()
    # 创建游标
    cursor=db.cursor()
    data=None
    try:
        cursor.execute(sql)
        data=cursor.fetchall()
        # print('已查询')
    except Exception as e:
        print(e)
    cursor.close()
    db.close()
    return data
# 写数据库
def write_data(sql):
    db=get_conn()
    cursor = db.cursor()
    rows=0
    try:
        rows=cursor.execute(sql)
        db.commit()
    except Exception as e:
        print(e)
    cursor.close()
    db.close()
    return rows
if __name__ == '__main__':
    print(get_conn())
    # 测试一下
    # sql="select * from products"
    # print(read_data(sql))
    # 测试一下
    sql="insert into products values(null,1005,'橙子','5','1')"
    print(write_data(sql))